/**
 * @Title: stationController.java
 * @Package tt.dz.mvc.controller.sys
 * @author pengyu
 * @date 2015年12月17日 上午10:21:55
 * @version V1.0
 */
package tt.dz.mvc.controller.sys;

import java.beans.IntrospectionException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import jxl.write.WriteException;
import tt.dz.dao.base.BaseDao;
import tt.dz.dao.ext.charger.OmsChargerChargeBillRecordDao;
import tt.dz.dao.ext.charger.OmsChargerDao;
import tt.dz.dao.ext.charger.OmsChargerStateAlternateDao;
import tt.dz.dao.ext.charger.OmsChargerStateDirectDao;
import tt.dz.entity.base.JsonCommon;
import tt.dz.entity.base.JsonForList;
import tt.dz.entity.base.JsonForMapDataList;
import tt.dz.entity.bigscreen.ScreenStation;
import tt.dz.entity.charger.OmsCharger;
import tt.dz.entity.charger.OmsChargerChargeBillRecord;
import tt.dz.entity.charger.OmsChargerStateAlternate;
import tt.dz.entity.charger.OmsChargerStateDirect;
import tt.dz.entity.station.IncomeVo;
import tt.dz.entity.station.OmsStation;
import tt.dz.entity.station.OmsStationLocation;
import tt.dz.entity.station.OutcomeVo;
import tt.dz.entity.system.ChargeInfoVo;
import tt.dz.mvc.controller.base.BaseController;
import tt.dz.service.base.OmsStationLocationService;
import tt.dz.service.imp.sys.ChargeDataUploadingVO;
import tt.dz.service.sys.OperStationService;
import tt.dz.service.sys.StationService;
import tt.dz.util.ActionUtils;
import tt.dz.util.Constants;
import tt.dz.util.ExcelExporter;
import tt.dz.util.OmsConstant;
import tt.dz.util.RedisClient;
import tt.dz.util.StringUtil;
import tt.dz.vo.oms.StationExportVO;

@Controller
public class StationController extends BaseController
{
	@Autowired
	StationService stationService;
	@Autowired
	OperStationService omsOperStationService;
	@Resource
	OmsChargerDao omsChargerDao;
	@Resource
	OmsChargerStateAlternateDao omsChargerStateAlternateDao;
	@Resource
	OmsChargerStateDirectDao omsChargerStateDirectDao;
	@Resource
	OmsStationLocationService omsStationLocationService;
	@Resource
	OmsChargerChargeBillRecordDao omsChargerChargeBillRecordDao;
	@Autowired
	@Qualifier("base")
	private BaseDao<OmsStationLocation> omsStationLocationDao;
	
	
	
	private Logger log = LoggerFactory.getLogger(StationController.class);
	// 1.自营站点列表接口
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getStationList")
	@ResponseBody
	public JsonForList getStationList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JsonForList isLogin = StringUtil.isLogin(request);
		if(isLogin.getCode().equals("400")){
			return isLogin;
		}
		// oper_merchant_id = 0
		// 就表示自营站点，1就表示第三方，其余就表示按oper_merchant_id的值精确查询,dao中暂时写死。
		String station_id = request.getParameter("station_id");
		String station_name = request.getParameter("station_name");// 模糊
		String oper_merchant_id = request.getParameter("oper_merchant_id");
		String district_code = request.getParameter("district_code");// 模糊
		String valid_flag = request.getParameter("valid_flag");
		String station_type = request.getParameter("station_type");
		String current_state = request.getParameter("current_state");
		String is_allow_open = request.getParameter("is_allow_open");
		
		OmsStation station = new OmsStation();
		if (StringUtil.isNotBlank(station_id)) {
			station.setStation_id(station_id);
		}
		if (StringUtil.isNotBlank(station_name)) {
			station.setStation_name(station_name);
		}
		if (StringUtil.isNotBlank(oper_merchant_id)) {
			station.setOper_merchant_id(oper_merchant_id);
		}
		if (StringUtil.isNotBlank(district_code)) {
			station.setDistrict_code(district_code);
		}
		if (StringUtils.isNumeric(valid_flag)) {
			station.setValid_flag(Integer.valueOf(valid_flag));
		}
		if (StringUtils.isNumeric(station_type)) {
			station.setStation_type(Integer.valueOf(station_type));
		}
		if (StringUtils.isNumeric(current_state)) {
			station.setCurrent_state(Integer.valueOf(current_state));
		}
		if (StringUtils.isNumeric(is_allow_open)) {
			station.setIs_allow_open(Integer.valueOf(is_allow_open));
		}
		HttpSession session = request.getSession();
		String login_oper_id = (String) session.getAttribute("login_oper_id");
		String login_entity_type = (String) session.getAttribute("login_entity_type");
		String login_super_flag = (String) session.getAttribute("login_super_flag");
//		if(StringUtil.isNumeric(login_entity_type) && login_entity_type.equals("0")){
//			login_oper_id = null ;//平台管理员查询就不需要查询用户与站的关联表
//		}
		if(StringUtil.isNumeric(login_super_flag) && login_super_flag.equals("1")){
			login_oper_id = null ;//平台管理员查询就不需要查询用户与站的关联表
		}
		return stationService.getStationList(station, login_oper_id);
	}
	//8.运营商接口:查询所有运营商  oms_operation_sp_list[充电运营服务商表]
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getOperMerchantList")
	@ResponseBody
	public JsonForList getOperMerchantList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JsonForList isLogin = StringUtil.isLogin(request);
		if(isLogin.getCode().equals("400")){
			return isLogin;
		}
		return stationService.findAllOperMerchant();
	}


	// 5.添加站点接口
	@SuppressWarnings("rawtypes")
	@RequestMapping("/addStation")
	@ResponseBody
	public JsonForList addStation(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JsonForList isLogin = StringUtil.isLogin(request);
		if(isLogin.getCode().equals("400")){
			return isLogin;
		}
		JsonForList json = new JsonForList();
		HttpSession session = request.getSession();
		String create_oper_id = request.getParameter("login_oper_id");//做假数据时用0000000000
		if(StringUtil.isBlank(create_oper_id)){
			create_oper_id = (String) session.getAttribute("login_oper_id");
		}
		OmsStation station = new OmsStation();
		String station_name = request.getParameter("station_name");
		String oper_merchant_id = request.getParameter("oper_merchant_id");// 充电运营服务商ID
		String district_code = request.getParameter("district_code");// 区县代码
		if(StringUtil.isBlank(station_name)||StringUtil.isBlank(oper_merchant_id)||StringUtil.isBlank(district_code)){
			json.setCode("400");
			json.setMsg("station_name or oper_merchant_id or district_code null");
			return json;
		}
		//查询district_code开头的站点，生成一个新ID。
		OmsStation station_query = new OmsStation();
		station_query.setOper_merchant_id(oper_merchant_id);
		station_query.setDistrict_code(district_code);
		String station_id_new = stationService.getNewStationId(station_query);
		station.setStation_id(station_id_new);
		station.setStation_name(station_name);
		station.setOper_merchant_id(oper_merchant_id);
		station.setDistrict_code(district_code);
		station.setDistrict_name(request.getParameter("district_name"));
		String current_state_str = request.getParameter("current_state");//当前状态
		if(StringUtil.isNotBlank(current_state_str)){
			Integer current_state = Integer.valueOf(current_state_str);
			station.setCurrent_state(current_state);
		}
		String circle = request.getParameter("circle");// 商圈/楼盘
		station.setCircle(circle);
		String coordtype_str = request.getParameter("coordtype");
//		if(StringUtil.isNotBlank(coordtype_str)){
//			Integer coordtype = Integer.valueOf(coordtype_str);// 地图类型
//			station.setCoordtype(coordtype);
//		}
//		String coordinate = request.getParameter("coordinate");// 坐标
//		station.setCoordinate(coordinate);
		String parking_type = request.getParameter("parking_type");// 停车处
		station.setParking_type(parking_type);
		String parking_addr = request.getParameter("parking_addr");// 停车处大体位置
		station.setParking_addr(parking_addr);
		String photo = request.getParameter("photo");// 环境照片URL路径
		station.setPhoto(photo);
		String total_charger_str = request.getParameter("total_charger");// 总电桩数
		if(StringUtil.isNotBlank(total_charger_str)){
			Integer total_charger = Integer.valueOf(total_charger_str);
			station.setTotal_charger(total_charger);
		}
		String establish_time_date = request.getParameter("establish_time");// 建立时间
		if(StringUtil.isNotBlank(establish_time_date)){
		       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		       try {
		          station.setEstablish_time(format.parse(establish_time_date));
		       } catch (ParseException e) {
		           e.printStackTrace();
		       }
		}
		String station_type_str = request.getParameter("station_type");// 站点类型
		if(StringUtil.isNotBlank(station_type_str)){
			Integer station_type = Integer.valueOf(station_type_str);
			station.setStation_type(station_type);
		}

		String is_allow_open = request.getParameter("is_allow_open");//  是否对外开放
		if(StringUtil.isNotBlank(is_allow_open)){
			Integer is_allow_open_int = Integer.valueOf(is_allow_open);
			station.setIs_allow_open(is_allow_open_int);
		}
		String address = request.getParameter("address");// 详细地址
		station.setAddress(address);
		String direct_num_str = request.getParameter("direct_num");//   直流桩数量
		if(StringUtil.isNotBlank(direct_num_str)){
			Integer direct_num = Integer.valueOf(direct_num_str);
			station.setDirect_num(direct_num);
		}
		String alternate_num_str = request.getParameter("alternate_num");//    交流桩数量
		if(StringUtil.isNotBlank(alternate_num_str)){
			Integer alternate_num = Integer.valueOf(alternate_num_str);
			station.setAlternate_num(alternate_num);
		}
		String tel_no = request.getParameter("tel_no");// 电话
		station.setTel_no(tel_no);
		String describes = request.getParameter("describes");// 站点描述
		station.setDescribes(describes);

		String entity_type = request.getParameter("entity_type");//
		if(StringUtil.isNotBlank(entity_type)){
			station.setEntity_type(entity_type);;
		}
		String entity_id = request.getParameter("entity_id");//
		if(StringUtil.isNotBlank(entity_id)){
			station.setEntity_id(entity_id);
		}
//		String valid_flag_str = request.getParameter("valid_flag");// 有效标记
//		if(StringUtil.isNotBlank(valid_flag_str)){
//			Integer valid_flag = Integer.valueOf(valid_flag_str);
//			station.setValid_flag(valid_flag);
//		}
		station.setValid_flag(1);
		Date create_time = new Date();// 创建时间
		station.setCreate_time(create_time);
		station.setCreate_oper_id(create_oper_id);// 创建人id
		
		JsonForList jsonForList = stationService.addStation(station);
		if (OmsConstant.SuccessCodeEnum.SuccessCode.value().equals(jsonForList.getCode())) {
			stationService.stationUpdateOrAddNotify(station);
		}
		return jsonForList;
	}

	// 6.修改站点接口
	@SuppressWarnings("rawtypes")
	@RequestMapping("/updateStation")
	@ResponseBody
	public JsonForList updateStation(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JsonForList isLogin = StringUtil.isLogin(request);
		if(isLogin.getCode().equals("400")){
			return isLogin;
		}
		HttpSession session = request.getSession();
		String update_oper_id = (String) session.getAttribute("login_oper_id"); // 更新人id
		JsonForList json = new JsonForList();
		OmsStation station = new OmsStation();
		String station_id = request.getParameter("station_id");
		if(StringUtil.isBlank(station_id)||StringUtil.isBlank(update_oper_id)){
			json.setCode("400");
			json.setMsg("station_id or oper_id null");
			return json;
		}



		String login_entity_type = (String) session.getAttribute("login_entity_type");
		OmsStation omsStation_check = new OmsStation();
		omsStation_check.setStation_id(station_id);
		JsonForList jsonforlist  = new JsonForList();
		if(StringUtil.isNumeric(login_entity_type) && login_entity_type.equals("0")){
			jsonforlist = stationService.getStationList(omsStation_check, null);
		}else if(StringUtil.isNumeric(login_entity_type) && !login_entity_type.equals("0")){
			jsonforlist = stationService.getStationList(omsStation_check, login_entity_type);
		}else{
			json.setCode("400");
			json.setMsg("please login");
			return json;
		}
		if(jsonforlist.getList()==null){
			json.setCode("400");
			json.setMsg("oper_id:"+update_oper_id+" do not own role or station_id not exist ");
			return json;
		}
//		OmsOperStation operStation = new OmsOperStation();
//		if(StringUtil.isNumeric(login_entity_type) && login_entity_type.equals("0")){
//			
//			operStation = omsOperStationService.query(station_id, null);//平台管理员查询就不需要查询用户与站的关联表
//		}else{
//			operStation = omsOperStationService.query(station_id, update_oper_id);
//		}
//		if(operStation==null){
//			json.setCode("400");
//			json.setMsg("oper_id:"+update_oper_id+" do not own role or station_id not exist ");
//			return json;
//		}
		Date update_time = new Date();// 更新时间
		station.setUpdate_time(update_time);
		station.setUpdate_oper_id(update_oper_id);
		station.setStation_id(station_id);
		String station_name = request.getParameter("station_name");
		station.setStation_name(station_name);
		String oper_merchant_id = request.getParameter("oper_merchant_id");// 充电运营服务商ID
		station.setOper_merchant_id(oper_merchant_id);
		String district_code = request.getParameter("district_code");// 区县代码
		station.setDistrict_code(district_code);
		station.setDistrict_name(request.getParameter("district_name"));
		String current_state_str = request.getParameter("current_state");//当前状态
		if(StringUtil.isNotBlank(current_state_str)){
			Integer current_state = Integer.valueOf(current_state_str);
			station.setCurrent_state(current_state);
		}
		String circle = request.getParameter("circle");// 商圈/楼盘
		station.setCircle(circle);
		String coordtype_str = request.getParameter("coordtype");
//		if(StringUtil.isNotBlank(coordtype_str)){
//			Integer coordtype = Integer.valueOf(coordtype_str);// 地图类型
//			station.setCoordtype(coordtype);
//		}
//		String coordinate = request.getParameter("coordinate");// 坐标
//		station.setCoordinate(coordinate);
		String parking_type = request.getParameter("parking_type");// 停车处
		station.setParking_type(parking_type);
		String parking_addr = request.getParameter("parking_addr");// 停车处大体位置
		station.setParking_addr(parking_addr);
		String photo = request.getParameter("photo");// 环境照片URL路径
		station.setPhoto(photo);
		String total_charger_str = request.getParameter("total_charger");// 总电桩数
		if(StringUtil.isNotBlank(total_charger_str)){
			Integer total_charger = Integer.valueOf(total_charger_str);
			station.setTotal_charger(total_charger);
		}
		String establish_time_date = request.getParameter("establish_time");// 建立时间
		if(StringUtil.isNotBlank(establish_time_date)){
		       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		       try {
		          station.setEstablish_time(format.parse(establish_time_date));
		       } catch (ParseException e) {
		           e.printStackTrace();
		       }
		}
		String station_type_str = request.getParameter("station_type");// 站点类型
		if(StringUtil.isNotBlank(station_type_str)){
			Integer station_type = Integer.valueOf(station_type_str);
			station.setStation_type(station_type);
		}
		String is_allow_open = request.getParameter("is_allow_open");//  是否对外开放
		if(StringUtil.isNotBlank(is_allow_open)){
			Integer is_allow_open_int = Integer.valueOf(is_allow_open);
			station.setIs_allow_open(is_allow_open_int);
		}
		String address = request.getParameter("address");// 详细地址
		station.setAddress(address);
		String direct_num_str = request.getParameter("direct_num");//   直流桩数量
		if(StringUtil.isNotBlank(direct_num_str)){
			Integer direct_num = Integer.valueOf(direct_num_str);
			station.setDirect_num(direct_num);
		}
		String alternate_num_str = request.getParameter("alternate_num");//    交流桩数量
		if(StringUtil.isNotBlank(alternate_num_str)){
			Integer alternate_num = Integer.valueOf(alternate_num_str);
			station.setAlternate_num(alternate_num);
		}
		String tel_no = request.getParameter("tel_no");// 电话
		station.setTel_no(tel_no);
		String describes = request.getParameter("describes");// 站点描述
		station.setDescribes(describes);
		String valid_flag_str = request.getParameter("valid_flag");// 有效标记
		if(StringUtil.isNotBlank(valid_flag_str)){
			Integer valid_flag = Integer.valueOf(valid_flag_str);
			station.setValid_flag(valid_flag);
		}
		station.setEntity_type(request.getParameter("entity_type"));
		station.setEntity_id(request.getParameter("entity_id"));
		
		JsonForList jsonForList = stationService.updateStation(station);
		if (OmsConstant.SuccessCodeEnum.SuccessCode.value().equals(jsonForList.getCode())) {
			stationService.stationUpdateOrAddNotify(station);
		}
		return jsonForList;
	}

	// 7.删除站点接口（批量） 只做逻辑删除
	@SuppressWarnings("rawtypes")
	@RequestMapping("/logicalDelStation")
	@ResponseBody
	public JsonForList logicalDelStation(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JsonForList isLogin = StringUtil.isLogin(request);
		if(isLogin.getCode().equals("400")){
			return isLogin;
		}
		JsonForList json = new JsonForList();
		//如果前台页面可以传list数组就传数组，不能的话就用,做为分隔符
		String stationIds = request.getParameter("stationIdList");
		if(StringUtil.isBlank(stationIds)){
			json.setCode("400");
			json.setMsg("stationIdList null");
			return json;
		}
		List<String> stationIdList = JSON.parseArray(stationIds, String.class);
		
		//判断该站是否还有绑定的桩
		List<Map<String, Object>> listCount = stationService.getNumberBindChargerOfStation(stationIdList);
		if(listCount.size()>0){
			String stationIdStr = "";
			for(Map<String, Object> map : listCount){
				stationIdStr = stationIdStr + map.get("station_id").toString() + ";";
			}
			json.setCode("400");
			json.setMsg("以下站点还有绑定的桩,请解绑后再删除:"+stationIdStr);
			return json;
		}
		JsonForList jsonForList = stationService.deleteStation(stationIdList);
		if (OmsConstant.SuccessCodeEnum.SuccessCode.value().equals(jsonForList.getCode())) {
			stationService.stationDeleteNotify(stationIdList);
		}
		return jsonForList;
	}

	@RequestMapping("/exportStation")
	public void exportStation(String stationIds, HttpServletResponse response) throws WriteException, InvocationTargetException, IntrospectionException, IllegalAccessException, IOException
	{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
		String fileName = String.format("oms_station_%1$s.xls", sdf.format(new Date()));
		String[] list_stationId = null;
		if (StringUtils.isNotEmpty(stationIds))
			list_stationId = stationIds.split(",");
		List<StationExportVO> list = stationService.getExportData(list_stationId);
		ExcelExporter excelExporter = new ExcelExporter();
		excelExporter.export(list, response, fileName);

	}

	// 1.首页实时数据接口
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getHomePageData")
	@ResponseBody
	public JsonCommon getHomePageData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JsonForList isLogin = StringUtil.isLogin(request);
		if(isLogin.getCode().equals("400")){
			JsonCommon json = new JsonCommon();
			json.setCode(isLogin.getCode());
			json.setMsg(isLogin.getMsg());
			return json;
		}
		String charger_type = request.getParameter("charger_type")==null?"":request.getParameter("charger_type");
		//查询数据：桩：上上月桩总数、上月桩总数、本月桩总数、本月预约数量、上月预约数量、本月充电数量、上月充电数量
		//站：电站总数、运营中数量、规划中数量、建设中数量
		//桩：桩总数、故障数量、充电数量、预约数量、空闲数量、离线数量。
		//返回数据：除了上上月桩总数换成上月桩增加数量外，其余就就是以上的
		return stationService.getHomePageData(charger_type);
	}
	// 1.地图初始化数据接口
	@SuppressWarnings("rawtypes")
	@RequestMapping("/mapDataInit")
	@ResponseBody
	public JsonForMapDataList mapDataInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JsonForList isLogin = StringUtil.isLogin(request);
		if(isLogin.getCode().equals("400")){
			JsonForMapDataList json = new JsonForMapDataList();
			json.setCode(isLogin.getCode());
			json.setMsg(isLogin.getMsg());
			return json;
		}
		//查询数据：
		//oms_station[站点表] oms_station_external[外部站点表] 总数
		//按条件查询站点数组，current_state = 1 就查询oms_station+oms_station_external，current_state = 2就是：安装中  current_state = 3 就是规划中，
		//  current_state = 9 就是current_state ！= 1  current_state = 0 就是查询全部
		String current_state = request.getParameter("current_state");
		return stationService.getMapDataInit(current_state);
	}

	@SuppressWarnings("rawtypes")
	@RequestMapping("/testExport")
	@ResponseBody
	public JsonForList testExport(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String fileName = StringUtil.now14time()+".xls";
		String[] Title={"机构ID","会员编号","类别",};
		List<Object> li = new ArrayList<Object>() ;
//		List<Object> li = new List<Object>() ;
		JsonCommon jsonC = new JsonCommon();
		jsonC.setCode("222");
		jsonC.setMsg("中午点");
		li.add(jsonC);
//		ExcelExporter.exportExcel(fileName, Title, li, response); TODO luoyp
		return null;
	}

	//充电次数统计
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getChargeCountSummary")
	@ResponseBody
	public JsonForList getChargeCountSummary(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String startdate = request.getParameter("startdate");
		String enddate = request.getParameter("enddate");
		String year = request.getParameter("year");
		String chargertype = request.getParameter("chargertype");
		String errormsg = validateSummaryInput(startdate, enddate, year, chargertype);
		JsonForList json;
		if (errormsg != null)
		{
			json = new JsonForList();
			json.setCode(JsonForList.FailCode);
			json.setMsg(errormsg);
		}
		else
			json = stationService.getChargecountSummary(startdate, enddate, year, chargertype);
		return json;
	}

	/**
	 * Validate the input in 2 ways
	 * 1. by date: start date and end date are mandatory and format should be yyyy-MM-dd
	 * 2. by year: year format should be yyyy
	 *
	 * @return error message, null if validation passed
	 */
	private String validateSummaryInput(String startdate, String enddate, String year, String chargertype)
	{
//		log.debug(startdate);
//		log.debug(enddate);
//		log.debug(year);
		if (!StringUtil.isBlank(chargertype))
		{
			if (!Constants.ChargerType.Direct.equals(chargertype) && !Constants.ChargerType.AC.equals(chargertype))
				return "Invalid charger type";
		}
		if (!StringUtil.isBlank(year))
		{
			if (!year.matches("\\d{4}"))
				return "Invalid year format";
		}
		else if(StringUtil.isNotBlank(startdate) && StringUtil.isNotBlank(enddate))
		{
//			if (StringUtil.isBlank(startdate) || StringUtil.isBlank(enddate))
//				return "Start date or end date should not be empty";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			try
			{
				Date dt_start = sdf.parse(startdate);
				Date dt_end = sdf.parse(enddate);
				if (dt_start.after(dt_end))
					return "Start date should be lesser than End date";
			}
			catch (ParseException ex)
			{
				return "Invalid date format";
			}
		}
		return null;
	}

	//成功预约次数统计
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getReserveCountSummary")
	@ResponseBody
	public JsonForList getReserveCountSummary(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String startdate = request.getParameter("startdate");
		String enddate = request.getParameter("enddate");
		String year = request.getParameter("year");
		String chargertype = request.getParameter("chargertype");
		String errormsg = validateSummaryInput(startdate, enddate, year, chargertype);
		JsonForList json;
		if (errormsg != null)
		{
			json = new JsonForList();
			json.setCode(JsonForList.FailCode);
			json.setMsg(errormsg);
		}
		else
			json = stationService.getReserveCountSummary(startdate, enddate, year, chargertype);
		return json;
	}

	//碳排放统计
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getCarbonEmissionSummary")
	@ResponseBody
	public JsonForList getCarbonEmissionSummary(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String startdate = request.getParameter("startdate");
		String enddate = request.getParameter("enddate");
		String year = request.getParameter("year");
		String chargertype = request.getParameter("chargertype");
		String errormsg = validateSummaryInput(startdate, enddate, year, chargertype);
		JsonForList json;
		if (errormsg != null)
		{
			json = new JsonForList();
			json.setCode(JsonForList.FailCode);
			json.setMsg(errormsg);
		}
		else
			json = stationService.getCarbonEmissionSummary(startdate, enddate, year, chargertype);
		return json;
	}
	
	
	
//	//大屏单站页 参数：站ID  必传   显示结果：年月日时分秒 星期几（前端实现） 
//	//返回结果：天气 温度 PM2.5 PM质量（好良差） 直流桩一个：充电中；预约中（包括预约B口的用户卡号）； 交流桩4个 至少一个是充电中；
//	@SuppressWarnings("rawtypes")
//	@RequestMapping("/getBigScreenByStationId")
//	@ResponseBody
//	public JsonCommon getBigScreenByStationId(HttpServletRequest request, HttpServletResponse response) throws Exception
//	{
//		String station_id = request.getParameter("station_id");
//		if (station_id == null)
//		{
//			return new JsonCommon(OmsConstant.ErrorCodeEnum.MissParam.value(), OmsConstant.ErrorCodeEnum.MissParam.desc());
//		}
//		ScreenStation ss = new ScreenStation();
//		ss.setStation_id(station_id);
//		//查询  6.12电池信息上送（可选）当前荷电状态	BIN码	1	系数为1%	0-100%  从redis中取得
//		//查询一个直流桩，两个口，一个预约，一个充电；查询4个交流桩，1个充电中，3个空闲。
//		//查询一个直流桩，两个口
//		List<OmsChargerStateDirect> directs ;
//		List<OmsChargerStateAlternate> alternates ;
//		OmsCharger charger_query = new OmsCharger();
//		charger_query.setStation_id(station_id);
//
//
//		StringBuilder condition_direct = new StringBuilder(" where 1 = 1 ");
//
//		List<OmsCharger> charger_list = omsChargerDao.findExample(charger_query, null, null, null, null);
//		if (charger_list != null && !charger_list.isEmpty())
//		{
//			condition_direct.append(" and charger_id in ( ");
//			for (OmsCharger charger : charger_list)
//			{
//				condition_direct.append(" '" + charger.getCharger_id() + "',");
//			}
//			condition_direct.deleteCharAt(condition_direct.length() - 1);
//			condition_direct.append(")");
//		}
//		else
//		{
//			condition_direct.append(" and 1 = 0");
//		}
//		directs = omsChargerStateDirectDao.findListByCondition(new OmsChargerStateDirect(), condition_direct.toString());
//
//		for (int i = 0; i < directs.size(); i++)
//		{
//			//查询redis
//			if (directs.get(i).getCharge_jrnl() == null)
//			{
//				continue;
//			}
//			OmsChargerChargeBillRecord chargeBillRecord_temp = omsChargerChargeBillRecordDao.findOneExample(new OmsChargerChargeBillRecord(directs.get(i).getCharge_jrnl()), null, null);
//			if (chargeBillRecord_temp == null)
//			{
//				continue;
//			}
//			//			String key_uploadChargeData = directs.get(i).getCharger_id()+ directs.get(i).getCharge_jrnl()+"_uploadChargeData";
//
//			String key_uploadChargeData = directs.get(i).getCharger_id() + String.format("%02d", directs.get(i).getPort_no()) + "_status";
//			String json = RedisClient.get(key_uploadChargeData);
//
//			if (json != null)
//			{
//				ChargeDataUploadingVO charging_vo = JSON.parseObject(json, ChargeDataUploadingVO.class);
//				String soc = charging_vo.getSoc();
//				directs.get(i).setSoc(soc);
//			}
//
//		}
//		StringBuilder condition_alternate = new StringBuilder(" where port_no = 1 ");
//
//		if(charger_list != null && !charger_list.isEmpty())
//		{
//			condition_alternate.append(" and charger_id in ( ");
//			for (OmsCharger charger : charger_list)
//			{
//				condition_alternate.append(" '" + charger.getCharger_id() + "',");
//			}
//			condition_alternate.deleteCharAt(condition_alternate.length() - 1);
//			condition_alternate.append(")");
//		}
//		else
//		{
//			condition_alternate.append(" and 1 = 0");
//		}
//		alternates = omsChargerStateAlternateDao.findListByCondition(new OmsChargerStateAlternate(), condition_alternate.toString());
//
//		if(alternates == null)
//			alternates = new ArrayList<>();
//		if(directs == null)
//			directs = new ArrayList<>();
//		ss.setAlternates(alternates);
//		ss.setDirects(directs);
//		//查询天气
//		//首先查询redis
//
//		String key = "baidu_weather";
//		String weather = "", city_temperature = "", pm25 = "", pm_level = "";
//		Map<String, String> map_fromRedis = RedisClient.getMap(key);
//		if (!map_fromRedis.isEmpty())
//		{
//			weather = map_fromRedis.get("weather");
//			city_temperature = map_fromRedis.get("city_temperature");
//			pm25 = map_fromRedis.get("pm25");
//			pm_level = map_fromRedis.get("pm_level");
//		}
//		else
//		{
//			String httpUrl = "http://apis.baidu.com/heweather/weather/free";
//			String httpArg = "cityid=CN101260101";//cityid=    city=guiyang
//			String jsonResult = ChargerController.request(httpUrl, httpArg);
//			JSONObject json = (JSONObject) JSON.parse(jsonResult);
//			//		System.out.println(jsonResult);
//			JSONArray heWeather_data_array = json.getJSONArray("HeWeather data service 3.0");
//			JSONObject daily_forecast_object = heWeather_data_array.getJSONObject(0);
//			//{"wind":{"dir":"东风","deg":"142","sc":"4-5","spd":"21"},"hum":"75","fl":"18","pcpn":"0","tmp":"17",
//			//"pres":"1011","cond":{"code":"101","txt":"多云"},"vis":"10"}
//			JSONObject now_object = daily_forecast_object.getJSONObject("now");
//			city_temperature = now_object.get("tmp").toString();
//			JSONObject cond_object = now_object.getJSONObject("cond");
//			weather = cond_object.get("txt").toString();
//			//{"city":{"co":"1","so2":"8","o3":"76","no2":"31","aqi":"64","pm10":"75","pm25":"33","qlty":"良"}}
//			JSONObject aqi_object = daily_forecast_object.getJSONObject("aqi");
//			JSONObject city_object = aqi_object.getJSONObject("city");
//			pm25 = city_object.get("pm25").toString();
//			pm_level = city_object.get("qlty").toString();
//
//			Map<String, String> map = new HashMap<String, String>();
//			map.put("weather", weather);
//			map.put("city_temperature", city_temperature);
//			map.put("pm25", pm25);
//			map.put("pm_level", pm_level);
//			RedisClient.putMap(key, map);
//			RedisClient.expire(key, 60 * 60);
//		}
//		ss.setWeather(weather);
//		ss.setCity_temperature(city_temperature);
//		ss.setPm25(pm25);
//		ss.setPm_level(pm_level);
//
//		return new JsonCommon(ss, OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc());
//
//	}
	
	//大屏单站页 参数：站ID  必传   显示结果：年月日时分秒 星期几（前端实现） 
	//返回结果：天气 温度 PM2.5 PM质量（好良差） 直流桩一个：充电中；预约中（包括预约B口的用户卡号）； 交流桩4个 至少一个是充电中；
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getBigScreenByStationId")
	@ResponseBody
	public JsonCommon getBigScreenByStationId(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String station_id = request.getParameter("station_id");
		if (station_id == null)
		{
			return new JsonCommon(OmsConstant.ErrorCodeEnum.MissParam.value(), OmsConstant.ErrorCodeEnum.MissParam.desc());
		}
		ScreenStation ss = new ScreenStation();
		ss.setStation_id(station_id);
		//查询  6.12电池信息上送（可选）当前荷电状态	BIN码	1	系数为1%	0-100%  从redis中取得
		//查询一个直流桩，两个口，一个预约，一个充电；查询4个交流桩，1个充电中，3个空闲。
		//查询一个直流桩，两个口
		List<OmsChargerStateDirect> directs ;
		List<OmsChargerStateAlternate> alternates ;
		OmsCharger charger_query = new OmsCharger();
		charger_query.setStation_id(station_id);


		StringBuilder condition_direct = new StringBuilder(" where 1 = 1 ");

		List<OmsCharger> charger_list = omsChargerDao.findExample(charger_query, null, null, null, null);
		if (charger_list != null && !charger_list.isEmpty())
		{
			condition_direct.append(" and charge_status in ('0','1','2') and charger_id in ( ");
			for (OmsCharger charger : charger_list)
			{
				condition_direct.append(" '" + charger.getCharger_id() + "',");
			}
			condition_direct.deleteCharAt(condition_direct.length() - 1);
			condition_direct.append(")");
		}
		else
		{
			condition_direct.append(" and 1 = 0");
		}
		directs = omsChargerStateDirectDao.findListByCondition(new OmsChargerStateDirect(), condition_direct.toString());

		for (int i = 0; i < directs.size(); i++)
		{
			//查询redis
			if (directs.get(i).getCharge_jrnl() == null)
			{
				continue;
			}
			OmsChargerChargeBillRecord chargeBillRecord_temp = omsChargerChargeBillRecordDao.findOneExample(new OmsChargerChargeBillRecord(directs.get(i).getCharge_jrnl()), null, null);
			if (chargeBillRecord_temp == null)
			{
				continue;
			}
			//			String key_uploadChargeData = directs.get(i).getCharger_id()+ directs.get(i).getCharge_jrnl()+"_uploadChargeData";

			String key_uploadChargeData = directs.get(i).getCharger_id() + String.format("%02d", directs.get(i).getPort_no()) + "_status";
			String json = RedisClient.get(key_uploadChargeData);

			if (json != null)
			{
				ChargeDataUploadingVO charging_vo = JSON.parseObject(json, ChargeDataUploadingVO.class);
				String soc = charging_vo.getSoc();
				directs.get(i).setSoc(soc);
			}

		}
		StringBuilder condition_alternate = new StringBuilder(" where port_no = 1 ");

		if(charger_list != null && !charger_list.isEmpty())
		{
			condition_alternate.append(" and charge_status in ('0','1','2') and charger_id in ( ");
			for (OmsCharger charger : charger_list)
			{
				condition_alternate.append(" '" + charger.getCharger_id() + "',");
			}
			condition_alternate.deleteCharAt(condition_alternate.length() - 1);
			condition_alternate.append(")");
		}
		else
		{
			condition_alternate.append(" and 1 = 0");
		}
		alternates = omsChargerStateAlternateDao.findListByCondition(new OmsChargerStateAlternate(), condition_alternate.toString());

		if(alternates == null)
			alternates = new ArrayList<>();
		if(directs == null){
			directs = new ArrayList<>();}
		ss.setAlternates(alternates);
		ss.setDirects(directs);
		//查询天气
		//首先查询redis

		String key = "baidu_weather";
		String weather = "", city_temperature = "", pm25 = "", pm_level = "";
		Map<String, String> map_fromRedis = RedisClient.getMap(key);
		if (!map_fromRedis.isEmpty())
		{
			weather = map_fromRedis.get("weather");
			city_temperature = map_fromRedis.get("city_temperature");
			pm25 = map_fromRedis.get("pm25");
			pm_level = map_fromRedis.get("pm_level");
		}
		else
		{
			String httpUrl = "http://apis.baidu.com/heweather/weather/free";
			String httpArg = "cityid=CN101260101";//cityid=    city=guiyang
			String jsonResult = ChargerController.request(httpUrl, httpArg);
			JSONObject json = (JSONObject) JSON.parse(jsonResult);
			//		System.out.println(jsonResult);
			JSONArray heWeather_data_array = json.getJSONArray("HeWeather data service 3.0");
			JSONObject daily_forecast_object = heWeather_data_array.getJSONObject(0);
			//{"wind":{"dir":"东风","deg":"142","sc":"4-5","spd":"21"},"hum":"75","fl":"18","pcpn":"0","tmp":"17",
			//"pres":"1011","cond":{"code":"101","txt":"多云"},"vis":"10"}
			JSONObject now_object = daily_forecast_object.getJSONObject("now");
			city_temperature = now_object.get("tmp").toString();
			JSONObject cond_object = now_object.getJSONObject("cond");
			weather = cond_object.get("txt").toString();
			//{"city":{"co":"1","so2":"8","o3":"76","no2":"31","aqi":"64","pm10":"75","pm25":"33","qlty":"良"}}
			JSONObject aqi_object = daily_forecast_object.getJSONObject("aqi");
			JSONObject city_object = aqi_object.getJSONObject("city");
			pm25 = city_object.get("pm25").toString();
			pm_level = city_object.get("qlty").toString();

			Map<String, String> map = new HashMap<String, String>();
			map.put("weather", weather);
			map.put("city_temperature", city_temperature);
			map.put("pm25", pm25);
			map.put("pm_level", pm_level);
			RedisClient.putMap(key, map);
			RedisClient.expire(key, 60 * 60);
		}
		ss.setWeather(weather);
		ss.setCity_temperature(city_temperature);
		ss.setPm25(pm25);
		ss.setPm_level(pm_level);

		return new JsonCommon(ss, OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc());

	}
	
	//通过站点ID查询 站下属所有桩的实时数据 
	//返回结果list： 已充电量、充电电压、充电电流、电池温度、开启时间、估计剩余时间、实际费用、枪口、SOC
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/getChargerStatusByStationIdAndChargerType")
	@ResponseBody  
	public JsonForList getChargerStatusByStationIdAndChargerType(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String station_id = request.getParameter("station_id");
		String charger_type = request.getParameter("charger_type");
		if(StringUtil.isBlank(station_id)||StringUtil.isBlank(charger_type)){
			return new JsonForList(null,OmsConstant.ErrorCodeEnum.MissParam.value(), OmsConstant.ErrorCodeEnum.MissParam.desc());
		}
		switch(charger_type){//设备电流类型:1--直流  2--交流 
		case "1":
			//先查询直流桩状态表
			String condition_d = " where charger_id in (select charger_id from oms_charger where valid_flag = 1 and station_id = '"+ station_id +"') order by port_no";
			List<OmsChargerStateDirect> list_d= omsChargerStateDirectDao.findListByCondition(new OmsChargerStateDirect(), condition_d);
			for(int i=0;i<list_d.size();i++){
				if(list_d.get(i).getCharge_status()==2){//0: 空闲;1: 预约;2 充电; 3 故障;4:占用中（针对双枪单充等情况）;5 刷卡中  8:离线
					//如果直流桩在充电中，就通过redis查询对应的soc
					String key_uploadChargeData = list_d.get(i).getCharger_id()+ list_d.get(i).getCharge_jrnl()+"_uploadChargeData";
					List  list_redis_uploadChargeData= RedisClient.getList(key_uploadChargeData);
					if(list_redis_uploadChargeData.size()>0){
						String temp = (String) list_redis_uploadChargeData.get(list_redis_uploadChargeData.size()-1);
						String[] temp_array = temp.split(",");
						String soc = temp_array[8];
						list_d.get(i).setSoc(StringUtil.isBlank(soc)?"75":soc);
					};
				}
			}
			return new JsonForList(list_d,OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc());
		case "2":
			String condition_a = " where charger_id in (select charger_id from oms_charger where valid_flag = 1 and station_id = '"+ station_id +"') order by port_no";
			List<OmsChargerStateAlternate> list_a= omsChargerStateAlternateDao.findListByCondition(new OmsChargerStateAlternate(), condition_a);
			return new JsonForList(list_a,OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc());
		default:
			return new JsonForList(null,OmsConstant.ErrorCodeEnum.ParamValueError.value(), OmsConstant.ErrorCodeEnum.ParamValueError.desc());
		}
	}
	
	//按电站ID或者电桩ID查询某时间段内充电次数
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getChargeCountById")
	@ResponseBody
	public JsonForList getChargeCountById(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String startdate = request.getParameter("startdate");
		String enddate = request.getParameter("enddate");
		String charger_id = request.getParameter("charger_id");
		String station_id = request.getParameter("station_id"); 
		String type = "";
		String id = "";
		String errormsg = null;
		
		if (StringUtil.isBlank(charger_id) && StringUtil.isBlank(station_id)) {
			errormsg = "ChargerID & StationID should not be all empty";
		} else if (StringUtil.isNotBlank(charger_id)) {
			type = "charger";
			id = charger_id;
		}else{
			type = "station";
			id = station_id;
		}
		if (StringUtil.isBlank(startdate) || StringUtil.isBlank(enddate))
			errormsg = "Start date or end date should not be empty";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try
		{
			Date dt_start = sdf.parse(startdate);
			Date dt_end = sdf.parse(enddate);
			if (dt_start.after(dt_end))
				errormsg =  "Start date should be lesser than End date";
		}
		catch (ParseException ex)
		{
			errormsg =  "Invalid date format";
		}
		
		JsonForList json;
		if (errormsg != null)
		{
			json = new JsonForList();
			json.setCode(JsonForList.FailCode);
			json.setMsg(errormsg);
		}
		else
			json = stationService.getChargeCountById(startdate, enddate, id, type);
		return json;
	}
	
	//按电站ID或者电桩ID查询某时间段内充电电量
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getChargekwhById")
	@ResponseBody
	public JsonForList getChargekwhById(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String startdate = request.getParameter("startdate");
		String enddate = request.getParameter("enddate");
		String charger_id = request.getParameter("charger_id");
		String station_id = request.getParameter("station_id"); 
		String type = "";
		String id = "";
		String errormsg = null;
		
		if (StringUtil.isBlank(charger_id) && StringUtil.isBlank(station_id)) {
			errormsg = "ChargerID & StationID should not be all empty";
		} else if (StringUtil.isNotBlank(charger_id)) {
			type = "charger";
			id = charger_id;
		}else{
			type = "station";
			id = station_id;
		}
		if (StringUtil.isBlank(startdate) || StringUtil.isBlank(enddate))
			errormsg = "Start date or end date should not be empty";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try
		{
			Date dt_start = sdf.parse(startdate);
			Date dt_end = sdf.parse(enddate);
			if (dt_start.after(dt_end))
				errormsg =  "Start date should be lesser than End date";
		}
		catch (ParseException ex)
		{
			errormsg =  "Invalid date format";
		}
		
		JsonForList json;
		if (errormsg != null)
		{
			json = new JsonForList();
			json.setCode(JsonForList.FailCode);
			json.setMsg(errormsg);
		}
		else
			json = stationService.getChargekwhById(startdate, enddate, id, type);
		return json;
	}
	
	//按电站ID或者电桩ID查询某时间段内充电费用
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getChargeAmountById")
	@ResponseBody
	public JsonForList getChargeAmountById(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String startdate = request.getParameter("startdate");
		String enddate = request.getParameter("enddate");
		String charger_id = request.getParameter("charger_id");
		String station_id = request.getParameter("station_id"); 
		String type = "";
		String id = "";
		String errormsg = null;
		
		if (StringUtil.isBlank(charger_id) && StringUtil.isBlank(station_id)) {
			errormsg = "ChargerID & StationID should not be all empty";
		} else if (StringUtil.isNotBlank(charger_id)) {
			type = "charger";
			id = charger_id;
		}else{
			type = "station";
			id = station_id;
		}
		if (StringUtil.isBlank(startdate) || StringUtil.isBlank(enddate))
			errormsg = "Start date or end date should not be empty";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try
		{
			Date dt_start = sdf.parse(startdate);
			Date dt_end = sdf.parse(enddate);
			if (dt_start.after(dt_end))
				errormsg =  "Start date should be lesser than End date";
		}
		catch (ParseException ex)
		{
			errormsg =  "Invalid date format";
		}
		
		JsonForList json;
		if (errormsg != null)
		{
			json = new JsonForList();
			json.setCode(JsonForList.FailCode);
			json.setMsg(errormsg);
		}
		else
			json = stationService.getChargeAmountById(startdate, enddate, id, type);
		return json; 
	}
	
	//按电站ID或者电桩ID查询某时间段内预约次数
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getReserveCountById")
	@ResponseBody
	public JsonForList getReserveCountById(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String startdate = request.getParameter("startdate");
		String enddate = request.getParameter("enddate");
		String charger_id = request.getParameter("charger_id");
		String station_id = request.getParameter("station_id"); 
		String type = "";
		String id = "";
		String errormsg = null;
		
		if (StringUtil.isBlank(charger_id) && StringUtil.isBlank(station_id)) {
			errormsg = "ChargerID & StationID should not be all empty";
		} else if (StringUtil.isNotBlank(charger_id)) {
			type = "charger";
			id = charger_id;
		}else{
			type = "station";
			id = station_id;
		}
		if (StringUtil.isBlank(startdate) || StringUtil.isBlank(enddate))
			errormsg = "Start date or end date should not be empty";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try
		{
			Date dt_start = sdf.parse(startdate);
			Date dt_end = sdf.parse(enddate);
			if (dt_start.after(dt_end))
				errormsg =  "Start date should be lesser than End date";
		}
		catch (ParseException ex)
		{
			errormsg =  "Invalid date format";
		}
		
		JsonForList json;
		if (errormsg != null)
		{
			json = new JsonForList();
			json.setCode(JsonForList.FailCode);
			json.setMsg(errormsg);
		}
		else
			json = stationService.getReserveCountById(startdate, enddate, id, type);
		return json;
	}
	
	//按电站ID或者电桩ID查询某时间段内预约总时长
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getReserveTimeById")
	@ResponseBody
	public JsonForList getReserveTimeById(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String startdate = request.getParameter("startdate");
		String enddate = request.getParameter("enddate");
		String charger_id = request.getParameter("charger_id");
		String station_id = request.getParameter("station_id"); 
		String type = "";
		String id = "";
		String errormsg = null;
		
		if (StringUtil.isBlank(charger_id) && StringUtil.isBlank(station_id)) {
			errormsg = "ChargerID & StationID should not be all empty";
		} else if (StringUtil.isNotBlank(charger_id)) {
			type = "charger";
			id = charger_id;
		}else{
			type = "station";
			id = station_id;
		}
		if (StringUtil.isBlank(startdate) || StringUtil.isBlank(enddate))
			errormsg = "Start date or end date should not be empty";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try
		{
			Date dt_start = sdf.parse(startdate);
			Date dt_end = sdf.parse(enddate);
			if (dt_start.after(dt_end))
				errormsg =  "Start date should be lesser than End date";
		}
		catch (ParseException ex)
		{
			errormsg =  "Invalid date format";
		}
		
		JsonForList json;
		if (errormsg != null)
		{
			json = new JsonForList();
			json.setCode(JsonForList.FailCode);
			json.setMsg(errormsg);
		}
		else
			json = stationService.getReserveTimeById(startdate, enddate, id, type);
		return json;
	}
	
	//按电站ID或者电桩ID查询某时间段内预约总费用
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getReserveAmountById")
	@ResponseBody
	public JsonForList getReserveAmountById(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String startdate = request.getParameter("startdate");
		String enddate = request.getParameter("enddate");
		String charger_id = request.getParameter("charger_id");
		String station_id = request.getParameter("station_id"); 
		String type = "";
		String id = "";
		String errormsg = null;
		
		if (StringUtil.isBlank(charger_id) && StringUtil.isBlank(station_id)) {
			errormsg = "ChargerID & StationID should not be all empty";
		} else if (StringUtil.isNotBlank(charger_id)) {
			type = "charger";
			id = charger_id;
		}else{
			type = "station";
			id = station_id;
		}
		if (StringUtil.isBlank(startdate) || StringUtil.isBlank(enddate))
			errormsg = "Start date or end date should not be empty";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try
		{
			Date dt_start = sdf.parse(startdate);
			Date dt_end = sdf.parse(enddate);
			if (dt_start.after(dt_end))
				errormsg =  "Start date should be lesser than End date";
		}
		catch (ParseException ex)
		{
			errormsg =  "Invalid date format";
		}
		
		JsonForList json;
		if (errormsg != null)
		{
			json = new JsonForList();
			json.setCode(JsonForList.FailCode);
			json.setMsg(errormsg);
		}
		else
			json = stationService.getReserveAmountById(startdate, enddate, id, type);
		return json; 
	}
	
	//按电站ID或电桩ID查询某一年内充电次数
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getYearChargeCountById")
	@ResponseBody
	public JsonForList getYearChargeCountById(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String year = request.getParameter("year");
		String charger_id = request.getParameter("charger_id");
		String station_id = request.getParameter("station_id"); 
		String type = "";
		String id = "";
		String errormsg = null;
		
		if (StringUtil.isBlank(charger_id) && StringUtil.isBlank(station_id)) {
			errormsg = "ChargerID & StationID should not be all empty";
		} else if (StringUtil.isNotBlank(charger_id)) {
			type = "charger";
			id = charger_id;
		}else{
			type = "station";
			id = station_id;
		}
		
		if (StringUtil.isBlank(year)){
			errormsg = "Year should not be empty";
		}else if (!year.matches("\\d{4}")){
				errormsg =  "Invalid year format";
		}
		
		JsonForList json;
		if (errormsg != null)
		{
			json = new JsonForList();
			json.setCode(JsonForList.FailCode);
			json.setMsg(errormsg);
		}
		else
			json = stationService.getYearChargeCountById(year, id, type);
		return json;
	}
	
	//按电站ID或电桩ID查询某一年内充电电量
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getYearChargekwhById")
	@ResponseBody
	public JsonForList getYearChargekwhById(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String year = request.getParameter("year");
		String charger_id = request.getParameter("charger_id");
		String station_id = request.getParameter("station_id"); 
		String type = "";
		String id = "";
		String errormsg = null;
		
		if (StringUtil.isBlank(charger_id) && StringUtil.isBlank(station_id)) {
			errormsg = "ChargerID & StationID should not be all empty";
		} else if (StringUtil.isNotBlank(charger_id)) {
			type = "charger";
			id = charger_id;
		}else{
			type = "station";
			id = station_id;
		}
		
		if (StringUtil.isBlank(year)){
			errormsg = "Year should not be empty";
		}else if (!year.matches("\\d{4}")){
				errormsg =  "Invalid year format";
		}
		
		JsonForList json;
		if (errormsg != null)
		{
			json = new JsonForList();
			json.setCode(JsonForList.FailCode);
			json.setMsg(errormsg);
		}
		else
			json = stationService.getYearChargekwhById(year, id, type);
		return json;
	}
	
	//按电站ID或电桩ID查询某一年内充电费用
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getYearChargeAmountById")
	@ResponseBody
	public JsonForList getYearChargeAmountById(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String year = request.getParameter("year");
		String charger_id = request.getParameter("charger_id");
		String station_id = request.getParameter("station_id"); 
		String type = "";
		String id = "";
		String errormsg = null;
		
		if (StringUtil.isBlank(charger_id) && StringUtil.isBlank(station_id)) {
			errormsg = "ChargerID & StationID should not be all empty";
		} else if (StringUtil.isNotBlank(charger_id)) {
			type = "charger";
			id = charger_id;
		}else{
			type = "station";
			id = station_id;
		}
		
		if (StringUtil.isBlank(year)){
			errormsg = "Year should not be empty";
		}else if (!year.matches("\\d{4}")){
				errormsg =  "Invalid year format";
		}
		
		JsonForList json;
		if (errormsg != null)
		{
			json = new JsonForList();
			json.setCode(JsonForList.FailCode);
			json.setMsg(errormsg);
		}
		else
			json = stationService.getYearChargeAmountById(year, id, type);
		return json; 
	}
	
	//按电站ID或者电桩ID查询某一年内预约次数
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getYearReserveCountById")
	@ResponseBody
	public JsonForList getYearReserveCountById(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String year = request.getParameter("year");
		String charger_id = request.getParameter("charger_id");
		String station_id = request.getParameter("station_id"); 
		String type = "";
		String id = "";
		String errormsg = null;
		
		if (StringUtil.isBlank(charger_id) && StringUtil.isBlank(station_id)) {
			errormsg = "ChargerID & StationID should not be all empty";
		} else if (StringUtil.isNotBlank(charger_id)) {
			type = "charger";
			id = charger_id;
		}else{
			type = "station";
			id = station_id;
		}
		
		if (StringUtil.isBlank(year)){
			errormsg = "Year should not be empty";
		}else if (!year.matches("\\d{4}")){
				errormsg =  "Invalid year format";
		}
		
		JsonForList json;
		if (errormsg != null)
		{
			json = new JsonForList();
			json.setCode(JsonForList.FailCode);
			json.setMsg(errormsg);
		}
		else
			json = stationService.getYearReserveCountById(year, id, type);
		return json;
	}
	
	//按电站ID或者电桩ID查询某一年内预约总时长
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getYearReserveTimeById")
	@ResponseBody
	public JsonForList getYearReserveTimeById(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String year = request.getParameter("year");
		String charger_id = request.getParameter("charger_id");
		String station_id = request.getParameter("station_id"); 
		String type = "";
		String id = "";
		String errormsg = null;
		
		if (StringUtil.isBlank(charger_id) && StringUtil.isBlank(station_id)) {
			errormsg = "ChargerID & StationID should not be all empty";
		} else if (StringUtil.isNotBlank(charger_id)) {
			type = "charger";
			id = charger_id;
		}else{
			type = "station";
			id = station_id;
		}
		
		if (StringUtil.isBlank(year)){
			errormsg = "Year should not be empty";
		}else if (!year.matches("\\d{4}")){
				errormsg =  "Invalid year format";
		}
		
		JsonForList json;
		if (errormsg != null)
		{
			json = new JsonForList();
			json.setCode(JsonForList.FailCode);
			json.setMsg(errormsg);
		}
		else
			json = stationService.getYearReserveTimeById(year, id, type);
		return json;
	}
	
	//按电站ID或者电桩ID查询某一年内预约总费用
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getYearReserveAmountById")
	@ResponseBody
	public JsonForList getYearReserveAmountById(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String year = request.getParameter("year");
		String charger_id = request.getParameter("charger_id");
		String station_id = request.getParameter("station_id"); 
		String type = "";
		String id = "";
		String errormsg = null;
		
		if (StringUtil.isBlank(charger_id) && StringUtil.isBlank(station_id)) {
			errormsg = "ChargerID & StationID should not be all empty";
		} else if (StringUtil.isNotBlank(charger_id)) {
			type = "charger";
			id = charger_id;
		}else{
			type = "station";
			id = station_id;
		}
		
		if (StringUtil.isBlank(year)){
			errormsg = "Year should not be empty";
		}else if (!year.matches("\\d{4}")){
				errormsg =  "Invalid year format";
		}
		
		JsonForList json;
		if (errormsg != null)
		{
			json = new JsonForList();
			json.setCode(JsonForList.FailCode);
			json.setMsg(errormsg);
		}
		else
			json = stationService.getYearReserveAmountById(year, id, type);
		return json; 
	}
	
	//按电站ID或者电桩ID查询概要：充电次数、充电电量、充电总费用、减少碳排放、预约次数、充电总时间、预约总费用
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getChargeSummaryById")
	@ResponseBody
	public JsonForList getChargeSummaryById(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String charger_id = request.getParameter("charger_id");
		String station_id = request.getParameter("station_id"); 
		String type = "";
		String id = "";
		String errormsg = null;
		
		if (StringUtil.isBlank(charger_id) && StringUtil.isBlank(station_id)) {
			errormsg = "ChargerID & StationID should not be all empty";
		} else if (StringUtil.isNotBlank(charger_id)) {
			type = "charger";
			id = charger_id;
		}else{
			type = "station";
			id = station_id;
		}
		
		JsonForList json;
		if (errormsg != null)
		{
			json = new JsonForList();
			json.setCode(JsonForList.FailCode);
			json.setMsg(errormsg);
		}
		else
			json = stationService.getChargeSummaryById(id, type);
		return json; 
	}
	//根据桩号查询桩坐标列表
	@SuppressWarnings("rawtypes")
	@RequestMapping("/findLocationByStationId")
	@ResponseBody
	public JsonForList findLocationByStationId(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
//		omsStationLocationService  findByStationId
 
		String station_id = request.getParameter("station_id"); 
		
		if (StringUtil.isBlank(station_id)) {
			return new JsonForList<>(null, OmsConstant.ErrorCodeEnum.MissParam.value(), OmsConstant.ErrorCodeEnum.MissParam.desc());
		}
		List<OmsStationLocation> list = omsStationLocationService.findByStationId(station_id);
		return new JsonForList<>(list, OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc()); 
	}
	//新增桩坐标
	@SuppressWarnings("rawtypes")
	@RequestMapping("/addLocation")
	@ResponseBody
	public JsonForList addLocation(OmsStationLocation omsStationLocation) throws Exception
	{
//		omsStationLocationDao.save(omsStationLocation);
		int result = omsStationLocationService.save(omsStationLocation);
		if(result>0){
			//通知AppServer更新它的本地站点信息
			List<OmsStation> stationList = stationService.getStationByIds(omsStationLocation.getStation_id());
			if (stationList.size()>0) {
				stationService.stationUpdateOrAddNotify(stationList.get(0));
			}
			return new JsonForList<>(null, OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc()); 
		}
		return new JsonForList<>(null, OmsConstant.ErrorCodeEnum.SqlExecException.value(), OmsConstant.ErrorCodeEnum.SqlExecException.desc()); 

	}
	
	//更新桩坐标
	@SuppressWarnings("rawtypes")
	@RequestMapping("/updateLocation")
	@ResponseBody
	public JsonForList updateLocation(OmsStationLocation omsStationLocation) throws Exception
	{
//		omsStationLocationService  findByStationId
		int result = omsStationLocationService.update(omsStationLocation);
		if(result>0){
			//通知AppServer更新它的本地站点信息
			List<OmsStation> stationList = stationService.getStationByIds(omsStationLocation.getStation_id());
			if (stationList.size()>0) {
				stationService.stationUpdateOrAddNotify(stationList.get(0));
			}
			return new JsonForList<>(null, OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc()); 
		}
		return new JsonForList<>(null, OmsConstant.ErrorCodeEnum.SqlExecException.value(), OmsConstant.ErrorCodeEnum.SqlExecException.desc()); 
	}
	
	
	//按电站ID查询：充站点地址、名称、所在地区、是否开放、当前状态、电桩总数、操作
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getSimpleStationList")
	@ResponseBody
	public JsonForList getSimpleStationList (HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		//电站ID可选
        String station_id = request.getParameter("station_id");

		return stationService.getSimpleStationList(station_id);
	}	
	
	//按电站ID查询：充站点地址、名称、所在地区、是否开放、当前状态、电桩总数、操作----------分页
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getSimpleStationPageList")
	@ResponseBody
	public JsonForList getSimpleStationPageList (HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		//电站ID：可选
        String stationId = request.getParameter("station_id");
        //是否开放：可选
        String isAllowOpen = request.getParameter("isAllowOpen");
        //当前状态：可选
        String currentState = request.getParameter("currentState");
        //搜索条件：可选
        String searchStr = request.getParameter("searchStr");
        if (StringUtil.isNotBlank(searchStr)) {
        	searchStr = new String(searchStr.getBytes("iso-8859-1"),"utf-8");
		}
        
		return stationService.getSimpleStationPageList(ActionUtils.buildQueryParam(request, true),stationId,isAllowOpen,currentState,searchStr);
	}	
	
	//按电站ID查询：站点所有字段，关联查询出运营商名称，合作商名称
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getStationDetailByStationId")
	@ResponseBody
	public JsonForList getStationDetailByStationId (HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String station_id = request.getParameter("station_id"); 

		String errormsg = null;
		
		if (StringUtil.isBlank(station_id)) {
			errormsg = "ChargerID & StationID should not be all empty";
		} 
		
		JsonForList json;
		if (errormsg != null)
		{
			json = new JsonForList();
			json.setCode(JsonForList.FailCode);
			json.setMsg(errormsg);
		}
		else
			json = stationService.getStationDetailByStationId(station_id);
		return json; 
	}

	//查询收入，可按开始时间和结束时间，默认当月
	@SuppressWarnings({ "rawtypes", "unchecked" })                  
	@RequestMapping("/getIncome")
	@ResponseBody
	public JsonCommon getIncome(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String startTime = request.getParameter("startTime"); 
		String endTime = request.getParameter("endTime"); 
		IncomeVo incomeVo = stationService.getIncome(startTime,endTime);
		return new JsonCommon(incomeVo, OmsConstant.successCode, OmsConstant.successMsg); 
	}
	//查询支出，可按开始时间和结束时间，默认当月
	@SuppressWarnings({ "rawtypes", "unchecked" })   
	@RequestMapping("/getOutcome")
	@ResponseBody
	public JsonCommon getOutcome(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String startTime = request.getParameter("startTime"); 
		String endTime = request.getParameter("endTime"); 
		OutcomeVo outcomeVo = stationService.getOutcome(startTime,endTime);
		return new JsonCommon(outcomeVo, OmsConstant.successCode, OmsConstant.successMsg); 
	}
	
	//查询充电电量和充电次数,通用方法
	@SuppressWarnings({ "rawtypes", "unchecked" })   
	@RequestMapping("/getChargeInfo")
	@ResponseBody
	public JsonCommon getChargeInfo(HttpServletRequest request, HttpServletResponse response) throws Exception
	{

		String defaultProviceCode = getFromCopyRight(request,"defaultProviceCode");
		log.info("defaultProviceCode = "+defaultProviceCode);
		String startTime = request.getParameter("startTime"); 
		String endTime = request.getParameter("endTime"); 
		String areaType = request.getParameter("areaType");//0为全国，1为省，2为市 
		String areaCode = request.getParameter("areaCode"); 
		ChargeInfoVo chargeInfoVo = stationService.getChargeInfoVo(defaultProviceCode,startTime,endTime,areaType,areaCode);
		return new JsonCommon(chargeInfoVo, OmsConstant.successCode, OmsConstant.successMsg); 
	}
	
	public String getFromCopyRight(HttpServletRequest request,String param){
		//CopyrightUtil  copyrightUtil =new CopyrightUtil();
		
		//return copyrightUtil.getCopyright();
		String filePath = "WEB-INF\\classes\\copyRight.properties";   
		//获取servlet的上下文    
		ServletContext context = request.getServletContext();   
		String webRootPath = context.getRealPath("\\");   
		//最后得到文件的绝对路径    
		String path = webRootPath+filePath ;    
	
		String classPath = this.getClass().getClassLoader().getResource("/").getPath();
	    String rootPath  = "";
	    //windows下
	    if("\\".equals(File.separator)){   
	        rootPath  = classPath.substring(1,classPath.indexOf("/WEB-INF/classes"));
	        rootPath = rootPath.replace("/", "\\");
	        path = rootPath+"\\WEB-INF\\classes\\copyRight.properties"  ;
	    }
	    //linux下
	    if("/".equals(File.separator)){   
	        rootPath  = classPath.substring(0,classPath.indexOf("/WEB-INF/classes"));
	        rootPath = rootPath.replace("\\", "/");
	        path = rootPath+"/WEB-INF/classes/copyRight.properties" ;;
	    }
		
	    log.info(path);
	    
        String value="";
        Properties prop =  new  Properties();  
        try  {
        //Reader in = new InputStreamReader(new FileInputStream("D:\\workspace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\dz_OMS_V2.1\\WEB-INF\\classes\\copyRight.properties"), "UTF-8");
        	Reader in = new InputStreamReader(new FileInputStream(path), "UTF-8");
            prop.load(in);  
            value = prop.getProperty(param).trim();  
        }  catch  (IOException e) {  
            e.printStackTrace();  
        } 
		return value;
	}
}
